﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AioNightly.Model;
using MySql.Data.MySqlClient;

namespace AioNightly.Dao
{
    public class ProductDAO
    {
        private void Read2List(MySqlDataReader reader, List<Product> list)
        {
            while (reader.Read())
            {
                Product it = new Product();
                it.Id = reader.GetInt32(0);
                it.Name = reader.GetString(1);

                list.Add(it);
            }
        }

        public List<Product> GetAllProducts()
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            List<Product> list = new List<Product>();
            string sql = string.Format("SELECT * FROM product");
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            Read2List(reader, list);

            if (reader != null)
                reader.Close();
            db.CloseConnection();

            return list;
        }

        public int AddProduct(string productName)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            string sql = string.Format("insert into product (productname) values('{0}')", productName);
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            int result = cmd.ExecuteNonQuery();

            return result;
        }
    }
}